package cn.itcast.netty.c1;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.sctp.nio.NioSctpServerChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

public class HelloServer {
    public static void main(String[] args) {
        //1.启动器，负责组装netty组件，启动服务
        new ServerBootstrap()
                //2.BossEventLoop,WorkerEventLoop(selector,thread),group组
                .group(new NioEventLoopGroup())
                //3.选择服务器的ServerSocketChannel实现
                .channel(NioServerSocketChannel.class) // OIO BIO
                //4.boss负责处理连接worker(child)负责处理读写的通道，决定了worker（child）能执行那些任务（handle）
                .childHandler(
                        //5.channel代表核客户端进行数据的读写操作通道的初始化，负责添加别的Handle
                        new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        //6.添加具体的handle
                        ch.pipeline().addLast(new StringDecoder());//将ByteBuffer转译为字符串
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){//自定义handle
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                System.out.println(msg);//将转译好的字符串打印
                            }
                        });
                    }
                }).bind(8080);//监听端口
    }
}
